import { useState, useEffect, useCallback, useRef } from "react";

import { BG_COLOR } from "~/constants";
import IconButton from "~/components/IconButton";
import CloseIcon from "~/components/icons/CloseIcon";
import styles from "./PostImage.module.css";

interface ImageViewerProps {
  images: string[];
  initialIndex: number;
  onClose: () => void;
}

export default function ImageViewer({
  images,
  initialIndex,
  onClose,
}: ImageViewerProps) {
  const [currentIndex, setCurrentIndex] = useState(initialIndex);
  const [scale, setScale] = useState(1);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const containerRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLImageElement>(null);

  // Handle keyboard events
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      } else if (e.key === "ArrowLeft") {
        prevImage();
      } else if (e.key === "ArrowRight") {
        nextImage();
      } else if (e.key === "+" || e.key === "=") {
        zoomIn();
      } else if (e.key === "-" || e.key === "_") {
        zoomOut();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [currentIndex, onClose]);

  const nextImage = useCallback(() => {
    setCurrentIndex((prev) => (prev + 1) % images.length);
    setScale(1); // Reset zoom when changing images
  }, [images.length]);

  const prevImage = useCallback(() => {
    setCurrentIndex((prev) => (prev - 1 + images.length) % images.length);
    setScale(1); // Reset zoom when changing images
  }, [images.length]);

  const zoomIn = useCallback(() => {
    setScale((prev) => Math.min(prev * 1.5, 5)); // Max 5x zoom
  }, []);

  const zoomOut = useCallback(() => {
    setScale((prev) => Math.max(prev / 1.5, 0.5)); // Min 0.5x zoom
  }, []);

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  // Handle double click on backdrop to reset zoom
  const handleBackdropDoubleClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      e.stopPropagation();
      // Reset zoom
      setScale(1);
      setPosition({ x: 0, y: 0 });
    }
  };

  // Click/tap to zoom at specific position
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();

    if (scale < 16) {
      // Zoom in - zoom to next level and center on click position
      const newScale = scale * 2;
      const rect = (e.target as HTMLImageElement).getBoundingClientRect();
      const clickX = e.clientX - rect.left;
      const clickY = e.clientY - rect.top;

      // Calculate the position to center the clicked point
      const centerX = rect.width / 2;
      const centerY = rect.height / 2;

      // Set position to center the clicked point
      setPosition({
        x: (centerX - clickX) * (newScale / scale - 1),
        y: (centerY - clickY) * (newScale / scale - 1),
      });

      setScale(newScale);
    } else {
      // Reset zoom when reaching 16x or on double click
      setScale(1);
      setPosition({ x: 0, y: 0 });
    }
  };

  // Double tap to reset zoom
  const handleDoubleTap = (e: React.MouseEvent) => {
    e.stopPropagation();
    // Reset zoom
    setScale(1);
    setPosition({ x: 0, y: 0 });
  };

  const currentImage = images[currentIndex];

  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        backgroundColor: "rgba(0, 0, 0, 0.9)",
        display: "flex",
        flexDirection: "column",
        zIndex: 1000,
      }}
      onClick={handleBackdropClick}
      onDoubleClick={handleBackdropDoubleClick}
    >
      {/* Header with close button */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          padding: "12px",
          backgroundColor: BG_COLOR,
        }}
      >
        <div style={{ color: "white" }}>
          {currentIndex + 1} / {images.length}
        </div>
        <IconButton onClick={onClose}>
          <CloseIcon style={{ color: "white" }} />
        </IconButton>
      </div>

      {/* Image viewer area */}
      <div
        ref={containerRef}
        style={{
          flex: 1,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          overflow: "hidden",
          position: "relative",
        }}
      >
        <img
          ref={imageRef}
          src={currentImage}
          className={styles.img}
          style={{
            maxWidth: "90vw",
            maxHeight: "80vh",
            transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
            transition: "transform 0.2s ease",
            cursor: scale > 1 ? "zoom-out" : "zoom-in",
          }}
          onClick={handleClick}
          onDoubleClick={handleDoubleTap}
        />
      </div>

      {/* Navigation controls */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          padding: "12px",
          backgroundColor: BG_COLOR,
        }}
      >
        <IconButton onClick={prevImage} disabled={images.length <= 1}>
          <svg
            viewBox="0 0 24 24"
            width="1.2em"
            height="1.2em"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <polyline points="15,18 9,12 15,6" />
          </svg>
        </IconButton>

        <div style={{ display: "flex", gap: "12px" }}>
          <IconButton onClick={zoomOut}>
            <svg
              viewBox="0 0 24 24"
              width="1.2em"
              height="1.2em"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <circle cx="12" cy="12" r="10" />
              <line x1="8" y1="12" x2="16" y2="12" />
            </svg>
          </IconButton>

          <IconButton onClick={zoomIn}>
            <svg
              viewBox="0 0 24 24"
              width="1.2em"
              height="1.2em"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <circle cx="12" cy="12" r="10" />
              <line x1="12" y1="8" x2="12" y2="16" />
              <line x1="8" y1="12" x2="16" y2="12" />
            </svg>
          </IconButton>
        </div>

        <IconButton onClick={nextImage} disabled={images.length <= 1}>
          <svg
            viewBox="0 0 24 24"
            width="1.2em"
            height="1.2em"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <polyline points="9,18 15,12 9,6" />
          </svg>
        </IconButton>
      </div>
    </div>
  );
}
